package com.andnnl.redis;

import cn.hutool.json.JSONUtil;
import com.andnnl.config.ConfigFileHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by chenss on 2020/8/28.
 */
public class RedisSessionTest {
    private static final Logger logger = LoggerFactory.getLogger(RedisSessionTest.class);
    static AtomicInteger atomicInteger = new AtomicInteger();

    public static void main(String[] args) throws Exception{
        RedisSession r = RedisSession.getRedisClient();
        //logger.info(r.get("sms25"));

        for (int i = 0; i < 4; i++) {
            String key = "key" + i;
            r.set(key, "test-" + i);
            logger.info(key + "-->" + r.get(key));
        }

//        test();
//        test3();
        testP();

//        test2();
    }

    private static void testP() {
        Long rs = RedisSession.operate(s -> s.publish("test.a1", "hello world"));
        System.out.println("publish rs:"+rs);
    }

    public static void test3() throws InterruptedException, ExecutionException, IOException {
//        IRedisService service = getService();

        long t1 = System.currentTimeMillis();
        for (int t = 0; t < 1000; t++) {
            int finalI=t;
            new Thread(()->{
                for (int k = 0; k < 2000; k++) {
                    //返回Null,表示操作失败
                    String rsStr = RedisSession.operate(s -> s.set("asdf" + finalI, "asdf" + finalI));
                    //                String rsStr = service.set("asdf" + finalI, "asdf" + finalI);
                    //                logger.info(rsStr);
                    int a=atomicInteger.incrementAndGet();
                    if(a%1000==0){
                        logger.info("count:" + a);
                    }
                    if (rsStr == null)
                        logger.info("" + finalI);
                }
            }).start();
        }

        long t2 = System.currentTimeMillis();
        logger.info("finish time:{}", t2 - t1);
        System.in.read();

    }

    public static void test() throws InterruptedException, ExecutionException, IOException {
//        IRedisService service = getService();

        long t1 = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(500);
        CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
        int tasks = 2000;
        for (int i = 0; i < tasks; i++) {
            int finalI = i;
//            completionService.submit(() -> System.out.println("asdf" + finalI), "aa" + finalI);
            completionService.submit(() -> {
//            executorService.submit(() -> {
                for (int k = 0; k < 500; k++) {
                        //返回Null,表示操作失败
                        String rsStr = RedisSession.operate(s -> s.set("asdf" + finalI, "asdf" + finalI));
        //                String rsStr = service.set("asdf" + finalI, "asdf" + finalI);
        //                logger.info(rsStr);
                        int a=atomicInteger.incrementAndGet();
                        if(a%1000==0){
                            logger.info("count:" + a);
                        }
                        if (rsStr == null)
                            logger.info("" + finalI);
                }
//
            }, "aa" + finalI);
        }
        for (int i = 0; i < tasks; i++) {
            String str = completionService.take().get();//先完成的结果先执行后续处理
            //do something
//            logger.info("finish->" + str);
        }
//        completionService.take().isDone();

        //汇总操作
        executorService.shutdown();
        long t2 = System.currentTimeMillis();
        logger.info("finish time:{}", t2 - t1);
        System.in.read();

    }

    private static IRedisService getService() {
        ConfigFileHelper c = new ConfigFileHelper("config");
        String ruc = c.getString("redis.use.cluster");
        boolean useCluster = ruc == null || "".equals(ruc) ? false : Boolean.parseBoolean(ruc);
        logger.info("redis.use.cluster={}", useCluster);
        String clusterStr = null;
        if (useCluster) {
            clusterStr = c.getString("redis.cluster");
            logger.info("redis.cluster={}", clusterStr);
        }
        return new RedisClusterServiceImpl(clusterStr);
    }

    private static void test2() {
        String rsStr = RedisSession.operate(s -> s.set("asdf", "asdf"));
        logger.info(rsStr);

        Long rs = RedisSession.operate(s -> s.del("asdf"));
        logger.info("" + rs);

        List<String> list = Arrays.asList("asdf1", "asdf2", "asdf3");
        List<String> rsStrList = RedisSession.operate(list, (s, b) -> s.set(b, b));
        logger.info(JSONUtil.toJsonStr(rsStrList));

        List<String> list2 = Arrays.asList("asdf1", "asdf2", "asdf3");
        List<Long> rsStrList2 = RedisSession.operate(list2, (s, b) -> s.del(b));
        logger.info(JSONUtil.toJsonStr(rsStrList2));

        //session.del("list");
        RedisSession.getRedisClient().lpush("27767529587889671719922901515223", "abc");
        RedisSession.getRedisClient().expire("27767529587889671719922901515223", 15);
        RedisSession.getRedisClient().lpush("27767529587889671719922901515223", "xzc");
        RedisSession.getRedisClient().expire("27767529587889671719922901515223", 15);
        RedisSession.getRedisClient().lpush("27767529587889671719922901515223", "erf");
        RedisSession.getRedisClient().expire("27767529587889671719922901515223", 15);
        RedisSession.getRedisClient().lpush("27767529587889671719922901515223", "bnh");
        RedisSession.getRedisClient().expire("27767529587889671719922901515223", 15);
        //LRANGE key start stop返回列表key中指定区间内的元素，区间以偏移量start和stop指定。下标(index)参数start和stop都以0为底，也就是说，以0表示列表的第一个元素，以1表示列表的第二个元素，以此类推。你也可以使用负数下标，以-1表示列表的最后一个元素，-2表示列表的倒数第二个元素，以此类推。
        List<String> listx = RedisSession.getRedisClient().lrange("27767529587889671719922901515223", 0, -1);
        for (int i = 0; i < listx.size(); i++) {
            logger.info("" + listx.get(i));
        }
    }

}
